package org.qengine.controller;

import lombok.extern.slf4j.Slf4j;
import org.qengine.entity.PaperRulesEntity;
import org.qengine.entity.QuestionEntity;
import org.qengine.service.PaperRulesService;
import org.qengine.service.PapersService;
import org.qengine.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("question")
public class QuestionController {
    @Autowired
    private QuestionService questionService;
    @Autowired
    private PaperRulesService paperRulesService;
    @Autowired
    private PapersService papersService;
    //增加单个题目
    @PostMapping("/addQuestion")
    public ResponseEntity<String> addQuestion(@RequestParam int typeID, @RequestParam int courseID, @RequestParam int knowledgeID, @RequestParam int dLevel, @RequestParam String questionStem, @RequestParam String questionAnswer) {
        int flag = questionService.addQuestion(typeID, courseID, knowledgeID, dLevel, questionStem, questionAnswer);
        if(flag == 1){
            return new ResponseEntity<>("添加成功", HttpStatus.OK);
        }
        return new ResponseEntity<>("添加失败", HttpStatus.BAD_REQUEST);
    }
    // 批量导入题目ByJson
    @PostMapping("/importQuestions")
    public ResponseEntity<String> importQuestions(@RequestBody List<QuestionEntity> questions) {
        try {
            // 调用服务层的导入方法
            int importedCount = questionService.importByJson(questions);
            // 构建响应信息
            String message = "成功导入 " + importedCount + " 道题目";
            return new ResponseEntity<>(message, HttpStatus.OK);
        } catch (Exception e) {
            // 捕获异常并返回错误信息
            return new ResponseEntity<>("导入题目失败: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    //使用文档导入
    @PostMapping("/importByDoc")
    public ResponseEntity<String> importByDoc(@RequestParam int courseID, @RequestParam("file") MultipartFile file) {
        if(file.isEmpty()) {
            return new ResponseEntity<>("文件不能为空", HttpStatus.BAD_REQUEST);
        }
        try {
            InputStream docInputStream = file.getInputStream();
            // 调用服务层的导入方法
            int importedCount = questionService.importByDoc(docInputStream, courseID);

            // 构建响应信息
            String message = "成功导入 " + importedCount + " 道题目";
            return new ResponseEntity<>(message, HttpStatus.OK);
        } catch (Exception e) {
            // 捕获异常并返回错误信息
            return new ResponseEntity<>("导入题目失败: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    //根据id删除题目
    @PostMapping("/deleteQuestionById")
    public ResponseEntity<String> deleteQuestionById(@RequestParam int id) {
        int flag = questionService.deleteQuestionById(id);
        if(flag == 1){
            return new ResponseEntity<>("删除成功", HttpStatus.OK);
        }
        return new ResponseEntity<>("没有题目可以删除", HttpStatus.BAD_REQUEST);
    }
    //根据课程id删除
    @PostMapping("/deleteQuestionByCourseId")
    public ResponseEntity<String> deleteQuestionByCourseId(@RequestParam int courseId) {
        int num =  questionService.deleteQuestionByCourseId(courseId);
        if(num >= 1){
            return new ResponseEntity<>("成功删除了"+num+"道题目", HttpStatus.OK);
        }
        return new ResponseEntity<>("没有题目可以删除", HttpStatus.BAD_REQUEST);
    }
    // 根据课程id和知识点id批量删除题目
    @PostMapping("/deleteQuestionByCourseIdAndKnowledgeId")
    public ResponseEntity<String> deleteQuestionByCourseIdAndKnowledgeId(@RequestParam int courseId, @RequestParam int knowledgeId) {
        int num = questionService.deleteQuestionByCourseIdAndKnowledgeId(courseId, knowledgeId);
        if(num >= 1){
            return new ResponseEntity<>("成功删除了"+num+"道题目", HttpStatus.OK);
        }
        return new ResponseEntity<>("没有题目可以删除", HttpStatus.BAD_REQUEST);
    }
    //根据id修改题目
    @PostMapping("/updateQuestionById")
    public ResponseEntity<String> updateQuestionById(@RequestParam int id, @RequestParam int typeID, @RequestParam int courseID, @RequestParam int knowledgeID, @RequestParam int dLevel, @RequestParam String questionStem, @RequestParam String questionAnswer) {
        int flag = questionService.updateQuestionById(id, typeID, courseID, knowledgeID, dLevel, questionStem, questionAnswer);
        try {
            if (flag > 0) {
                return new ResponseEntity<>("修改成功", HttpStatus.OK);
            }
            return new ResponseEntity<>("没有对应题目，已添加新题", HttpStatus.OK);
        }catch (Exception e){
            return new ResponseEntity<>("修改失败", HttpStatus.BAD_REQUEST);
        }
    }
    //根据课程查询所有题目
    @GetMapping("/selectQuestionByCourseId")
    public List<QuestionEntity> selectQuestionByCourseId(@RequestParam int CourseId) {
        return questionService.selectQuestionByCourseId(CourseId);
    }
    //动态查询
    @GetMapping("/dynamicSelect")
    public List<QuestionEntity> dynamicSelect(@RequestParam(required = false) Integer typeId,@RequestParam(required = false) Integer courseId,  @RequestParam(required = false) Integer knowledgeId, @RequestParam(required = false) Integer dLevel) {
            return questionService.dynamicSelect(typeId, courseId, knowledgeId, dLevel);
    }
    //考题去重
    @PostMapping("/removeDuplicateQuestions")
    public ResponseEntity<String> removeDuplicateQuestionsByCourseId(@RequestParam(required = false) Integer courseId) {
        try {
            List<Integer> IDs = null;
            // 调用服务层的导入方法
            if(courseId == null){
                IDs = questionService.DeduplicationQuestion();
            }else{
                IDs = questionService.DeduplicationQuestionByCourseId(courseId);
            }
            String message;
            if(IDs != null && !IDs.isEmpty()){
                StringBuilder listCount = new StringBuilder(" ");
                for (Integer id : IDs) {
                    listCount.append(" ").append(Integer.toString(id));

                }
                // 构建响应信息
                message = "去除的题目id: " + listCount;
            }else{
                message = "该课程下没有重复题目";
            }
            return new ResponseEntity<>(message, HttpStatus.OK);
        } catch (Exception e) {
            // 捕获异常并返回错误信息
            return new ResponseEntity<>("考题查重失败: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/Training")
    public ResponseEntity<?> GenerateTrainingByMistakes(@RequestParam Long userId,@RequestParam Long ruleId) {
        PaperRulesEntity randomRule = null;
        List<QuestionEntity> result1 = null;
        try {
            log.info("GenerateTrainingByMistakesRequest received for ruleId: {}", ruleId,",userId: {}", userId);
            try{
                result1 = paperRulesService.GeneratePaper(ruleId);
            }catch (Exception e){
                e.printStackTrace();
            }
            log.info("GenerateTrainingByCourseIdResponse returned: {}", result1);
            papersService.savePapers(result1, ruleId,"Training");
            return ResponseEntity.ok(result1);
        } catch (Exception e) {
            log.error("Error occurred while generating Training paper: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error generating Training paper");
        }
    }
}
